package com.lingjtx.common.core.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class BeanUtil {

    /**
     * Entity实体转化Map对象
     *
     * @param bean Entity实体
     * @return HashMap
     */
    public static Map<String, Object> covertMap(Object bean) {
        if (Objects.isNull(bean)) return null;
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = bean.getClass();
        Field[] fields = clazz.getDeclaredFields();
        copy(bean, clazz, map, fields);

        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz!=null) {
            Field[] superFields = superClazz.getDeclaredFields();
            copy(bean, superClazz, map, superFields);
        }
        return map;
    }

    private static Map<String, Object> copy(Object bean, Class<?> clazz, Map<String, Object> map, Field[] fields) {
        for (Field field : fields) {
            String key = field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
            try {
                Object value = clazz.getMethod("get" + key).invoke(bean);
                if (value != null) {
                    map.put(field.getName(), value);
                }
            } catch (Exception e) {
                return null;
            }
        }
        return map;
    }
}
